<?php

namespace App\Http\Controllers\V1\Admin;

use App\Models\V1\Admins;
use App\Models\V1\Users;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\YourDataImport;

// 自定义的导入类
use Illuminate\Support\Facades\DB;

use Illuminate\Http\Request;

class ExcelController extends BaseController
{

    public function uploadUsers(Request $request)
    {
        $user_id = $request->input('user_id');
        $user_data = Admins::select('id', 'community_id')->find($user_id)->toArray();
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls,csv'
        ]);
        $file = $request->file('file');



        // 在 try 块外提前验证文件数据
        $rows = Excel::toArray([], $file)[0]; // 解析文件为数组
        if (empty($rows) || count($rows) < 2) {
            return response()->json(['message' => '导入文件为空或格式不正确'], 400);
        }

        // 去掉第一行表头
        $data = array_slice($rows, 1);

        // 提取文件中的电话号码列 (假设电话号码在第3列，即索引为2)
        $fileMobiles = array_column($data, 2);

        // 查询数据库中已存在的电话号码
        $existingMobiles = Users::whereIn('mobile', $fileMobiles)->pluck('mobile')->toArray();
        $duplicateMobilesString = implode(', ', $existingMobiles);


        // 检查是否有重复的电话号码
        if (!empty($existingMobiles)) {
            return response()->json([
                'message' => '导入文件中存在与数据库重复的电话号码'.$duplicateMobilesString,
                'duplicates' => $existingMobiles,
            ], 400);
        }


        DB::beginTransaction();

        try {

            $import = new YourDataImport($user_data);
            Excel::import($import, $file);
            DB::commit();
            return response()->json(['message' => '导入成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage(), 'error' => $e->getMessage()], 500);
        }
    }
}
